//
//  HYHttps.m
//  HaiYue
//
//  Created by skyline on 2018/6/19.
//  Copyright © 2018年 skyline. All rights reserved.
//

#import "HYHttps.h"
#import <AFNetworking.h>
@implementation HYHttps
+ (AFHTTPSessionManager *)manager
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 10;
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];//普通格式
    //    manager.requestSerializer = [AFJSONRequestSerializer serializer]; //JSON格式
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];//AFN不解析，以data返回
    //    manager.responseSerializer = [AFJSONResponseSerializer serializer]; // AFN会JSON解析返回的数据
    return manager;
}

+ (void)get:(NSString *)api para:(id)para complete:(complete)complete fail:(fail)fail
{
    AFHTTPSessionManager *manager = [self manager];
    // get请求也可以直接将参数放在字典里，AFN会自己讲参数拼接在url的后面，不需要自己拼接
    [manager GET:[HYHttps url:api] parameters:para progress:^(NSProgress * _Nonnull downloadProgress)
     {
         
     }
         success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
     {
         if (responseObject)
         {
             NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
             complete(dict);
         }
         else
         {
             complete(nil);
         }
     }
         failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
     {
         fail(@{@"code":@(error.code),@"msg":error.localizedDescription});
     }];
}
+ (void)post:(NSString *)api para:(id)para complete:(complete)complete fail:(fail)fail
{
    id newpara = [self pjPara:para];
    AFHTTPSessionManager *manager = [self manager];
    // get请求也可以直接将参数放在字典里，AFN会自己讲参数拼接在url的后面，不需要自己凭借
    [manager POST:[HYHttps url:api] parameters:newpara progress:^(NSProgress * _Nonnull downloadProgress)
     {
         
     }
          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
     {
         if (responseObject)
         {
             NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
             if ([[dict valueForKey:@"retcode"] intValue] == 2002)
             {
                 [CCAlert showMessage:@"登录超时" title:@"" enter:^{
                     UIViewController *vc = [UIViewController presentedViewController:nil];
                     if (vc)
                     {
                         return  [vc.navigationController pushViewController:[NSClassFromString(@"HYLoginViewController") new] animated:YES];
                     }
                 }];
             }
             else
                 complete(dict);
         }
         else
         {
             complete(nil);
         }
     }
          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
     {
         fail(@{@"code":@(error.code),@"msg":error.localizedDescription});
     }];
}

+ (void)post:(NSString *)api para:(id)para completeWithTask:(callback)callback fail:(fail)fail
{
    id newpara = [self pjPara:para];
    AFHTTPSessionManager *manager = [self manager];
    // get请求也可以直接将参数放在字典里，AFN会自己讲参数拼接在url的后面，不需要自己凭借
    [manager POST:[HYHttps url:api] parameters:newpara progress:^(NSProgress * _Nonnull downloadProgress)
     {
         
     }
          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
     {
         if (responseObject)
         {
             NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
             if ([[dict valueForKey:@"retcode"] intValue] == 2002)
             {
                 [CCAlert showMessage:@"登录超时" title:@"" enter:^{
                     UIViewController *vc = [[[UIView alloc] init] superViewController];
                     if (vc)
                     {
                         return  [vc.navigationController pushViewController:[NSClassFromString(@"HYLoginViewController") new] animated:YES];
                     }
                 }];
             }
             else
                 callback(task, dict);
         }
         else
         {
             callback(task, nil);
         }
     }
          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
     {
         fail(@{@"code":@(error.code),@"msg":error.localizedDescription});
     }];
}

+(void)upload:(NSString *)api para:(id)para image:(UIImage *)image progress:(progressNum )progress complete:(complete)complete fail:(fail)fail
{
    NSData *imageData = UIImageJPEGRepresentation(image, 0.1);//image为要上传的图片(UIImage)
    AFHTTPSessionManager *manager = [self manager];
    id newpara = [self pjPara:para];
    [manager POST:[HYHttps url:api] parameters:newpara constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData)
     {
         NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
         formatter.dateFormat = @"yyyyMMddHHmmss";
         NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
         //二进制文件，接口key值，文件路径，图片格式
         [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpg/png/jpeg"];
     } progress:^(NSProgress * _Nonnull uploadProgress)
     {
         progress(uploadProgress);
     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
     {
         if (responseObject)
         {
             NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
             complete(dict);
         }
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
     {
         fail(@{@"code":@(error.code),@"msg":error.localizedDescription});
         
     }];
}
+ (NSString *)url:(NSString *)api
{
//    NSString *server = ([AppDelegate shareAppDelegate].server_V == APPServerLocal)?SERVERLINK_LOCAL:SERVERLINK_ONLINE;
//    return [NSString stringWithFormat:@"%@%@",server,api];
    return @"";
}

+ (NSDictionary *)pjPara:(NSDictionary *)para
{
    if (para == nil && [[HYUserManager manager].user.accesstoken length] < 1)
        return @{@"terminal":@"1"};
    else if (para == nil && [[HYUserManager manager].user.accesstoken length] > 1)
        return @{@"terminal":@"1",@"accesstoken":[HYUserManager manager].user.accesstoken};
    NSMutableDictionary *para1 = [[[NSMutableDictionary alloc] initWithDictionary:para] insertDict:@{@"terminal":@"1"}];
    return [para1 insertDict:@{@"accesstoken":([[HYUserManager manager].user.accesstoken length] > 1)?[HYUserManager manager].user.accesstoken:@""}];
}
- (void)AFNetworkStatus{
    
    //1.创建网络监测者
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    
    /*枚举里面四个状态  分别对应 未知 无网络 数据 WiFi
     typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
     AFNetworkReachabilityStatusUnknown          = -1,      未知
     AFNetworkReachabilityStatusNotReachable     = 0,       无网络
     AFNetworkReachabilityStatusReachableViaWWAN = 1,       蜂窝数据网络
     AFNetworkReachabilityStatusReachableViaWiFi = 2,       WiFi
     };
     */
    
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        //这里是监测到网络改变的block  可以写成switch方便
        //在里面可以随便写事件
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未知网络状态");
                break;
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"无网络");
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"蜂窝数据网");
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"WiFi网络");
                
                break;
                
            default:
                break;
        }
        
    }] ;
}
@end
